<?php

namespace App\Http\Middleware\Api;

use App\Models\User;
use Closure;
use Jenssegers\Agent\Agent;

class LoginLog
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(\Illuminate\Http\Request $request, Closure $next)
    {
        $response = $next($request);

        if ($response->getStatusCode() === 201) { // 登录成功
            $user = auth()->user();
            $status = 1;
            $msg = '用户登录成功';
        } else {
            $user = User::where('name', $request->input('name'))->first(); // 登录失败
            $status = 2;
            $msg = $response->getData()->data;
        }

        if ($user) {
            $geo = geoip($request->ip())->toArray();
            $agent = new Agent();
            $platform = $agent->platform();

            $user->logs()->create([
                'ip' => $request->ip(),
                'address' => $geo['city'] ?? '',
                'os' => ($platform . ' ' . $agent->version($platform)) ?: '未知',
                'status' => $status,
                'msg' => $msg
            ]);
        }

        return $response;
    }
}
